//@ sourceURL=weiya-user.js
$(function () {
    var columns = [
        {
            checkbox: true
        }, {
            field: 'username',
            title: '用户名',
            align: "center"
        }, {
            field: 'email',
            title: '邮箱',
            align: "center"
        }, {
            field: 'phone',
            title: '电话',
            align: "center",
        },
        {
            field: 'status',
            title: '用户状态',
            align: "center",
            formatter: function (value, row, index) {
                var text = '-';
                if (value == 1) {
                    text = "启用";
                } else if (value == 2) {
                    text = "禁用";
                } else if (value == 3) {
                    text = "已删除";
                }
                return text;
            }
        },
        {
            field: 'lastLoginTime',
            title: '最后登录时间',
            align: "center",
            formatter: function (value, row, index) {
                return Global.longMsTimeConvertToDateTime(value);
            }
        },
        {
            field: 'operation',
            title: '操作',
            align: "center",
            formatter: function (value, row, index) {
                var edit = editFlag=="true" ?  '<a class="table-btn table-btn-info" href="javascript:void(0)" onclick="editUser(' + row.userId + ')">编辑</a>' : '';
                var assign = assignRoleFlag=="true" ? '<a class="table-btn table-btn-info"  href="javascript:void(0)" onclick="assignRoleList(' + row.userId + ')">分配角色</a>' : '';
                var del = deleteFlag=="true" ? '<a class="table-btn table-btn-danger" href="javascript:void(0)" onclick="deleteUser(' + row.userId + ',' + row.status + ')">删除</a>' : '';
                return edit + assign + del;
            }
        }];

    // 条件查询参数
    function queryParams(params) {
        var temp = { //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            limit: params.limit, //页面大小
            offset: params.offset, //页码
            username: $("#username").val(),
            email: $("#email").val(),
            phone: $("#phone").val(),
            status: $("#status").val()
        };
        return temp;
    }

    var options = {
        id: "#table",
        url: '/user/list',
        columns: columns,
        toolbar: '#toolbar',
        showRefresh: true,
        queryParams: queryParams
    }
    // 初始化列表数据
    Global.initTable(options);

    // 点击查询按钮
    $("#queryBtn").click(function () {
        Global.refreshTable("#table");
    });
    // 点击重置按钮
    $("#resetBtn").click(function () {
        // $("#queryForm")[0].reset();
        Global.clearForm("queryForm");
    });

    // 每次点新增用户的时候先清除表单错误提示
    $("#addBtn").click(function () {
        Global.clearError("#userForm");
    });

    // 保存新增用戶
    $("#saveUserBtn").click(function () {
        if (doValidForm(userForm)) {
            Global.mask("#saveUserBtn");
            Global.postAjax(
                "/user/add",
                $("#userForm").serialize(),
                function (data) {
                    Global.unmask("#saveUserBtn");
                    if (data.code == 200) {
                        $("#userModal").modal("hide");
                        $("#userForm")[0].reset();
                        Global.refreshTable("#table")
                    }
                    layer.msg(data.msg);
                })
        }
    });


});

// 删除用户
function deleteUser(userId, status) {
    if (status == 3) {
        layer.msg("请勿重复删除数据!");
        return;
    }
    Global.confirm("确定删除该用户？", function () {
        Global.postAjax(
            "/user/delete",
            {"userId": userId},
            function (data) {
                if (data.code == 200) {
                    Global.refreshTable("#table");
                }
                layer.msg(data.msg);
            }, "get")
    })
}

// 批量删除用户
$("#batch-delete-btn").click(function () {
    var checkedRows = Global.selectMutiData("#table");
    if (checkedRows) {
        var result = true;
        $.each(checkedRows, function (i, item) {
            if (item.status == 3) {
                layer.msg("请勿重复删除数据!");
                result = false;
            }
        });
        if (!result) {
            return; // 该return只会跳出方法
        }
        Global.confirm("确定删除选中的" + checkedRows.length + "条记录？", function () {
            var userIdStr = "";
            $.each(checkedRows, function (i, item) {
                userIdStr += (item.userId + ",");
            });
            userIdStr = userIdStr.substring(0, userIdStr.length - 1);
            Global.postAjax(
                "/user/batch/delete",
                {"userIdStr": userIdStr},
                function (data) {
                    if (data.code == 200) {
                        Global.refreshTable("#table");
                    }
                    layer.msg(data.msg);
                }, "get")
        })
    }
});

// 分配用户角色
$("#saveAssign").click(function () {
    // var checkedRows = Global.selectMutiData("#assignRoleTable");
    var checkedRows= $("#assignRoleTable").bootstrapTable('getSelections');
    if (checkedRows) {
        Global.mask("#saveAssign");
        var roleIdStr = "";
        $.each(checkedRows, function (i, item) {
            roleIdStr += (item.roleId + ",");
        })
        roleIdStr = roleIdStr.substring(0, roleIdStr.length - 1);
        Global.postAjax(
            '/user/assign/role',
            {userId: userIdChecked, roleIdStr: roleIdStr},
            function (data) {
                Global.unmask("#saveAssign");
                if (data.code == 200) {
                    $("#assignRoleModal").modal("hide");
                }
                layer.msg(data.msg);
            })
    }
});

// 编辑用户信息
function editUser(userId) {
    Global.load("#userOpenWindow", "/user/edit/" + userId, function () {
        $("#userDetailModal").modal("show");
    }, 2);
}

var userIdChecked;
var loadRoleCount = 0;
var selectRoleIds;

// 根据用户id查询用户角色
function queryRoleParams(params) {
    var temp = {
        userId: userIdChecked
    };
    return temp;
}

// 分配角色初始化
function assignRoleList(userId) {
    userIdChecked = userId;
    $("#assignRoleModal").modal("show");
    if (loadRoleCount == 0) {
        var roleColumns = [
            {checkbox: true},
            {
                field: 'roleId',
                title: '角色ID',
                align: "center"
            }, {
                field: 'name',
                title: '角色名称',
                align: "center"
            }, {
                field: 'description',
                title: '角色描述',
                align: "center"
            },
            {
                field: 'status',
                title: '角色状态',
                align: "center",
                formatter: function (value, row, index) {
                    var text = '-';
                    if (value == 1) {
                        text = "有效";
                    } else if (value == 2) {
                        text = "无效";
                    } else if (value == 3) {
                        text = "已删除";
                    }
                    return text;
                }
            }];
        var roleOptions = {
            id: "#assignRoleTable",
            url: "/user/assign/role/list",
            columns: roleColumns,
            pagination: false,
            queryParams: queryRoleParams,
            onLoadSuccess: function () {  //加载成功时执行
                loadRoleCount = 1;
                Global.checkTableBy("#assignRoleTable", {field: "roleId", values: selectRoleIds});
            },
            // 加载服务器数据之前的处理程序，可以用来格式化数据。参数：res为从服务器请求到的数据。
            responseHandler: handleRoleData,
        }
        Global.initTable(roleOptions);
    }
    if (loadRoleCount == 1) {
        Global.refreshTable("#assignRoleTable");
    }
}

// 处理角色数据
function handleRoleData(res) {
    selectRoleIds = res.hasRoles;
    return res.rows;
}
